<?php
namespace wap\controllers;

use Yii;
use common\helps\api;

/**
 * Site controller
 */
class CartController extends CommonController
{
    //购物车列表
    public function actionIndex()
    {

//        $result = api::post('materiel/get-cart', $param);
//        $retData = array();
//        if ($result['code'] == 200) {
//            $retData = $result['data'];
//        }


        $retData = $this->getCartGoodsByShopId();

        $userInfo = $this->getLoginUser();


        return $this->render('index', ['cartArr' => $retData, 'shopType' => $userInfo['shopType']]);
    }


    private function getCartGoodsByShopId()
    {

        $user = $this->getCache('USER');
        $param = array(
            'userId' => $user['userName'],
            'shopId' => $user['shopId'],
        );

        $res_warehouse = api::post('comm/get-warehouses', $user['shop']);
        $res_goods = api::post('materiel/get-cart', $param);

        $new_goods = array();
        if ($res_warehouse['code'] == 200 && $res_goods['code'] == 200) {
            $warehouses = $res_warehouse['data'];
            $goods = $res_goods['data'];
            $waresouseIds = array_column($warehouses, 'id');
            foreach ($goods as $good) {
                if (in_array($good['warehouseId'], $waresouseIds)) {
                    $new_goods [] = $good;
                }
            }
        }
        return $new_goods;
    }



    //编辑购物车
    public function actionAddCart()
    {
        $data = Yii::$app->request->post();
        if(!isset($data['list']) || empty($data['list']) || !is_array($data['list'])) $this->retJson('参数错误', 500);
        $user = $this->getCache('USER');
        $param = array(
            'userId' => $user['userName'],
            'list' => $data['list']
        );
        api::post('materiel/add-cart', $param);
        $this->retJson('ok', 200);
    }

    //缓存商品信息
    public function actionGoBuy()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['goods']) || !is_array($data['goods'])) {
            $this->retJson('参数错误', 500);
        }
        $orderGoods = $data['goods'];
        $this->setCache('ORDER_GOODS', $orderGoods, 72000);
        $this->retJson('ok', 200);
    }
}
